package org.csu.mypetstore.util;

import lombok.extern.slf4j.Slf4j;
import org.csu.mypetstore.commonResponse.CommonResponse;

import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;


@ControllerAdvice
@Slf4j//通过日志框架在服务器打印出异常情况
public class GlobalExceptionHandler {

    org.slf4j.Logger logger= LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(MissingServletRequestParameterException.class)//声明捕获的异常类型
    @ResponseStatus(code= HttpStatus.BAD_REQUEST)//设置一场状态码
    @ResponseBody
    public CommonResponse<Object> handleMissingServletRequestParameterException(MissingServletRequestParameterException e){
        logger.error(e.getMessage());
        return CommonResponse.createForError("缺少参数");
    }


    @ExceptionHandler(Exception.class)//声明捕获的异常类型 总异常
    @ResponseStatus(code= HttpStatus.INTERNAL_SERVER_ERROR)//设置一场状态码
    @ResponseBody
    public CommonResponse<Object> handleException(Exception e){
        logger.error(e.getMessage());
        return CommonResponse.createForError("服务器异常");
    }
}
